from rest_framework import serializers
from .models import *
from goods.serializers import GoodSerializer
import random
import time

class ShoppingCartDetailSerializer(serializers.ModelSerializer):
    goods = GoodSerializer()
    class Meta:
        model = ShoppingCart
        fields = '__all__'

class ShoppingCartSerializer(serializers.Serializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    goods = serializers.PrimaryKeyRelatedField(required=True, queryset=Goods.objects.all())
    nums = serializers.IntegerField(required=True, min_value=1)

    def create(self, validated_data):
        user = self.context['request'].user
        goods = validated_data['goods']
        nums = validated_data['nums']
        records = ShoppingCart.objects.filter(user=user,goods=goods)
        if records:
            record = records[0]
            record.nums += nums
            record.save()
        else:
            record = ShoppingCart.objects.create(**validated_data)
        return record

    def update(self, instance, validated_data):
        instance.nums = validated_data['nums']
        instance.save()
        return instance
    class Meta:
        model = ShoppingCart
        fields = '__all__'


class OrderGoodSerializer(serializers.ModelSerializer):
    goods = GoodSerializer()
    class Meta:
        model = OrderGoods
        fields = '__all__'

class OrderInfoSerializer2(serializers.ModelSerializer):
    goods = OrderGoodSerializer(many=True)
    class Meta:
        model = OrderInfo
        fields = '__all__'

class OrderInfoSerializer1(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    order_sn = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    add_time = serializers.DateTimeField(read_only=True)

    def generate_order_sn(self):
        order_sn = str(int(time.time())) + \
                   str(self.context['request'].user.id)+\
                   str(random.randint(1000,9999))
        return order_sn
    def validate(self, attrs):
        attrs['order_sn'] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = '__all__'